<?php

namespace EthanZ\LaravelExt\Models\Traits;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Arr;

/**
 * 返回数据降维
 *
 * @package EthanZ\LaravelExt\Models\Traits
 */
trait GetSetColumns
{


    /**
     * 批量赋值
     *
     * @param Builder $query
     * @param array   $columnsData
     * @param array   $unsetData
     * @param string  $method
     *
     * @return object|array
     */
    public function scopeGetSetColumns(Builder $query, array $columnsData, array $unsetData, string $method = 'get'): object|array
    {
        switch ($method) {
            case 'get' || 'page':
                $data = $method === 'get' ? $query->get() : $query->page();
                foreach (($method === 'get' ? $data : $data['list']) as $v) {
                    $this->getSetColumns($v, $columnsData, $unsetData);
                }
                break;

            case 'find':
                $data = $query->first();
                if ($data) {
                    $this->getSetColumns($data, $columnsData, $unsetData);
                }
                break;
            default:
                $data = (object)[];
                break;
        }

        return $data;
    }


    /**
     * 赋值
     *
     * @param       $data
     * @param array $columnsData
     * @param array $unsetData
     */
    private function getSetColumns($data, array $columnsData, array $unsetData): void
    {
        $dataDot = Arr::dot($data->toArray());
        foreach ($columnsData as $ke => $va) {
            $data->$va = $dataDot[$ke];
        }
        foreach ($unsetData as $va) {
            unset($data->$va);
        }
    }
}